package com.kmdd.xtds.util

import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch


/**
 * 封装Activity的Launch调用，捕获未知异常。
 */
fun AppCompatActivity.launch(
    onError: (Throwable) -> Unit = { Log.i("launch", "未处理的异常: ${it.message}") },
    block: suspend CoroutineScope.() -> Unit,
): Job {
    return lifecycleScope.launch(CoroutineExceptionHandler { _, throwable ->
        //转换异常具体信息
        onError(throwable)
    }) {
        block()
    }
}

/**
 * 封装Activity的Launch调用，捕获未知异常。
 */
fun Fragment.launch(
    onError: (Throwable) -> Unit = { Log.i("launch", "未处理的异常: ${it.message}") },
    block: suspend CoroutineScope.() -> Unit,
): Job {
    return lifecycleScope.launch(CoroutineExceptionHandler { _, throwable ->
        //转换异常具体信息
        onError(throwable)
    }) {
        block()
    }
}